package library

import (
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"os"
	"path"
	"path/filepath"
	"vip_video/configx"
)

type SystemFileLibrary struct {
	StorageBasePath string
}

type SystemFileOption func(sf *SystemFileLibrary)

func NewSystemFileLibrary(opts ...SystemFileOption) *SystemFileLibrary {
	s := &SystemFileLibrary{}
	for _, opt := range opts {
		opt(s)
	}
	return s
}

func WithStorageBasePath(path string) SystemFileOption {
	return func(sf *SystemFileLibrary) {
		sf.StorageBasePath = path
	}
}

// DownloadFile 下载文件到本地
func (sfl *SystemFileLibrary) DownloadFile(u string) (string, error) {
	request := NewRequestLibrary(
		WithUrl(u),
	)
	response, err := request.Get()
	if err != nil {
		return "", err
	}
	defer response.Body.Close()
	data, err := io.ReadAll(response.Body)
	if err != nil {
		return "", err
	}
	filePath, err := filepath.Abs(fmt.Sprintf("%s%s", sfl.StorageBasePath, path.Base(u)))
	if err != nil {
		return "", err
	}
	if err := os.WriteFile(filePath, data, 0644); err != nil {
		return "", err
	}
	return filePath, nil
}

// Upload2System 上传文件到系统
func (sfl *SystemFileLibrary) Upload2System(p string) (string, error) {
	request := NewRequestLibrary(
		WithUrl(fmt.Sprintf("%s/api/common/upload", configx.C.BackEnd.Host)),
	)
	response, err := request.UploadFile(p)
	if err != nil {
		return "", err
	}
	defer response.Body.Close()
	data, err := io.ReadAll(response.Body)
	if err != nil {
		return "", err
	}
	var responseData map[string]any
	if err := json.Unmarshal(data, &responseData); err != nil {
		return "", err
	}
	if code, ok := responseData["code"]; ok {
		if code = code.(float64); code == 0 {
			if msg, ok := responseData["msg"]; ok {
				return "", errors.New(fmt.Sprintf("上传文件[%s],错误:[%s]", p, msg.(string)))
			} else {
				return "", errors.New("未知错误")
			}
		}
	} else {
		return "", errors.New("系统错误,backend api返回有问题")
	}
	if d, ok := responseData["data"]; ok {
		if dd, ok := d.(map[string]any); ok {
			return dd["url"].(string), nil
		}
	}
	return "", errors.New("系统错误")
}
